import ApiService from './ApiService.js';

class OrderStore {
  constructor() {
    this.orders = [];
    this.listeners = [];
    this.isLoading = false;
    this.error = null;
    
    // 从本地存储加载数据
    this.loadFromLocalStorage();
  }

  // 添加监听器
  addListener(listener) {
    this.listeners.push(listener);
  }

  // 移除监听器
  removeListener(listener) {
    this.listeners = this.listeners.filter(l => l !== listener);
  }

  // 通知所有监听器
  notifyListeners() {
    this.listeners.forEach(listener => listener());
  }

  // 保存数据到本地存储
  saveToLocalStorage() {
    localStorage.setItem('orders', JSON.stringify(this.orders));
  }

  // 从本地存储加载数据
  loadFromLocalStorage() {
    const savedOrders = localStorage.getItem('orders');
    if (savedOrders) {
      try {
        this.orders = JSON.parse(savedOrders);
      } catch (error) {
        console.error('Failed to parse orders from localStorage:', error);
        this.orders = [];
      }
    } else {
      // 如果本地存储没有数据，使用默认数据
      this.orders = this.getDefaultOrders();
      this.saveToLocalStorage();
    }
  }

  // 获取默认订单数据
  getDefaultOrders() {
    return [
      {
        id: 1,
        orderNumber: 'ORD-20231115-001',
        customerName: '张三',
        customerPhone: '13800138001',
        customerAddress: '北京市朝阳区建国路88号',
        orderDate: '2023-11-15T10:30:00',
        status: 'delivered',
        totalAmount: 5899,
        paymentMethod: '支付宝',
        paymentStatus: true,
        paymentDate: '2023-11-15T10:35:00',
        products: [
          { id: 2, name: '7寸穿越机', price: 3299, quantity: 1, image: 'https://picsum.photos/seed/drone1/200/200' },
          { id: 6, name: '无人机电池', price: 399, quantity: 6, image: 'https://picsum.photos/seed/battery1/200/200' }
        ]
      },
      {
        id: 2,
        orderNumber: 'ORD-20231114-002',
        customerName: '李四',
        customerPhone: '13900139002',
        customerAddress: '上海市浦东新区张江高科技园区',
        orderDate: '2023-11-14T14:20:00',
        status: 'shipped',
        totalAmount: 4599,
        paymentMethod: '微信支付',
        paymentStatus: true,
        paymentDate: '2023-11-14T14:25:00',
        products: [
          { id: 3, name: '10寸穿越机', price: 4599, quantity: 1, image: 'https://picsum.photos/seed/drone2/200/200' }
        ]
      },
      {
        id: 3,
        orderNumber: 'ORD-20231113-003',
        customerName: '王五',
        customerPhone: '13700137003',
        customerAddress: '广州市天河区天河路385号',
        orderDate: '2023-11-13T09:15:00',
        status: 'processing',
        totalAmount: 3299,
        paymentMethod: '支付宝',
        paymentStatus: true,
        paymentDate: '2023-11-13T09:20:00',
        products: [
          { id: 7, name: '遥控器', price: 1299, quantity: 1, image: 'https://picsum.photos/seed/remote1/200/200' },
          { id: 8, name: 'FPV眼镜', price: 2999, quantity: 1, image: 'https://picsum.photos/seed/goggles1/200/200' }
        ]
      },
      {
        id: 4,
        orderNumber: 'ORD-20231112-004',
        customerName: '赵六',
        customerPhone: '13600136004',
        customerAddress: '深圳市南山区科技园',
        orderDate: '2023-11-12T16:45:00',
        status: 'pending',
        totalAmount: 12999,
        paymentMethod: '银行转账',
        paymentStatus: false,
        products: [
          { id: 5, name: '工业级无人机', price: 12999, quantity: 1, image: 'https://picsum.photos/seed/industrial1/200/200' }
        ]
      },
      {
        id: 5,
        orderNumber: 'ORD-20231111-005',
        customerName: '钱七',
        customerPhone: '13500135005',
        customerAddress: '杭州市西湖区文三路',
        orderDate: '2023-11-11T20:10:00',
        status: 'canceled',
        totalAmount: 2899,
        paymentMethod: '微信支付',
        paymentStatus: true,
        paymentDate: '2023-11-11T20:15:00',
        products: [
          { id: 1, name: '5寸穿越机', price: 2899, quantity: 1, image: 'https://picsum.photos/seed/drone3/200/200' }
        ]
      },
      {
        id: 6,
        orderNumber: 'ORD-20231110-006',
        customerName: '孙八',
        customerPhone: '13400134006',
        customerAddress: '南京市鼓楼区中山路',
        orderDate: '2023-11-10T11:30:00',
        status: 'delivered',
        totalAmount: 597,
        paymentMethod: '支付宝',
        paymentStatus: true,
        paymentDate: '2023-11-10T11:35:00',
        products: [
          { id: 9, name: '备用螺旋桨', price: 129, quantity: 3, image: 'https://picsum.photos/seed/propeller1/200/200' },
          { id: 10, name: '便携收纳包', price: 499, quantity: 1, image: 'https://picsum.photos/seed/bag1/200/200' }
        ]
      },
      {
        id: 7,
        orderNumber: 'ORD-20231109-007',
        customerName: '周九',
        customerPhone: '13300133007',
        customerAddress: '成都市锦江区春熙路',
        orderDate: '2023-11-09T13:20:00',
        status: 'processing',
        totalAmount: 5899,
        paymentMethod: '微信支付',
        paymentStatus: true,
        paymentDate: '2023-11-09T13:25:00',
        products: [
          { id: 4, name: '超轻固定翼', price: 5899, quantity: 1, image: 'https://picsum.photos/seed/plane1/200/200' }
        ]
      }
    ];
  }

  // 加载订单数据（异步）
  async loadOrders() {
    this.isLoading = true;
    this.error = null;
    
    try {
      // 尝试从API获取数据
      const data = await ApiService.getOrders();
      
      if (data && data.length > 0) {
        this.orders = data;
        this.saveToLocalStorage();
      }
    } catch (error) {
      console.error('Failed to load orders from API:', error);
      this.error = error.message;
      
      // 如果API失败，使用本地存储的数据或默认数据
      if (this.orders.length === 0) {
        this.orders = this.getDefaultOrders();
      }
    } finally {
      this.isLoading = false;
      this.notifyListeners();
    }
  }

  // 获取所有订单
  getAllOrders() {
    return this.orders;
  }

  // 根据ID获取订单
  getOrderById(id) {
    return this.orders.find(order => order.id === id);
  }

  // 按状态获取订单
  getOrdersByStatus(status) {
    return this.orders.filter(order => order.status === status);
  }

  // 处理订单状态变更
  async updateOrderStatus(id, newStatus) {
    try {
      // 尝试通过API更新状态
      const success = await ApiService.updateOrderStatus(id, newStatus);
      
      if (success) {
        // 更新本地数据
        const index = this.orders.findIndex(order => order.id === id);
        if (index !== -1) {
          this.orders[index].status = newStatus;
          // 如果订单从处理中变为已发货，添加发货日期
          if (newStatus === 'shipped') {
            this.orders[index].shippingDate = new Date().toISOString();
          }
          // 如果订单从已发货变为已送达，添加送达日期
          if (newStatus === 'delivered') {
            this.orders[index].deliveryDate = new Date().toISOString();
          }
          
          this.saveToLocalStorage();
          this.notifyListeners();
        }
        return true;
      }
      return false;
    } catch (error) {
      console.error('Failed to update order status via API:', error);
      
      // API失败时，尝试在本地更新
      try {
        const index = this.orders.findIndex(order => order.id === id);
        if (index !== -1) {
          this.orders[index].status = newStatus;
          // 如果订单从处理中变为已发货，添加发货日期
          if (newStatus === 'shipped') {
            this.orders[index].shippingDate = new Date().toISOString();
          }
          // 如果订单从已发货变为已送达，添加送达日期
          if (newStatus === 'delivered') {
            this.orders[index].deliveryDate = new Date().toISOString();
          }
          
          this.saveToLocalStorage();
          this.notifyListeners();
          return true;
        }
        return false;
      } catch (localError) {
        console.error('Failed to update order status locally:', localError);
        throw localError;
      }
    }
  }

  // 取消订单
  async cancelOrder(id) {
    return this.updateOrderStatus(id, 'canceled');
  }

  // 搜索订单
  searchOrders(query) {
    const lowerQuery = query.toLowerCase();
    return this.orders.filter(order => 
      order.orderNumber.toLowerCase().includes(lowerQuery) ||
      order.customerName.toLowerCase().includes(lowerQuery)
    );
  }

  // 获取订单统计数据
  getOrderStats() {
    const total = this.orders.length;
    const pending = this.orders.filter(order => order.status === 'pending').length;
    const processing = this.orders.filter(order => order.status === 'processing').length;
    const shipped = this.orders.filter(order => order.status === 'shipped').length;
    const delivered = this.orders.filter(order => order.status === 'delivered').length;
    const canceled = this.orders.filter(order => order.status === 'canceled').length;
    
    const totalRevenue = this.orders
      .filter(order => order.status !== 'canceled')
      .reduce((sum, order) => sum + order.totalAmount, 0);
    
    return {
      total,
      pending,
      processing,
      shipped,
      delivered,
      canceled,
      totalRevenue
    };
  }
  
  // 添加新订单
  async addOrder(order) {
    try {
      // 尝试通过API添加订单
      const success = await ApiService.addOrder(order);
      
      if (success) {
        // 更新本地数据
        this.orders.unshift(order);
        this.saveToLocalStorage();
        this.notifyListeners();
        return true;
      }
      return false;
    } catch (error) {
      console.error('Failed to add order via API:', error);
      
      // API失败时，尝试在本地添加
      try {
        this.orders.unshift(order);
        this.saveToLocalStorage();
        this.notifyListeners();
        return true;
      } catch (localError) {
        console.error('Failed to add order locally:', localError);
        throw localError;
      }
    }
  }
  
  // 更新订单
  async updateOrder(updatedOrder) {
    try {
      // 尝试通过API更新订单
      const success = await ApiService.updateOrder(updatedOrder);
      
      if (success) {
        // 更新本地数据
        const index = this.orders.findIndex(order => order.id === updatedOrder.id);
        if (index !== -1) {
          this.orders[index] = updatedOrder;
          this.saveToLocalStorage();
          this.notifyListeners();
        }
        return true;
      }
      return false;
    } catch (error) {
      console.error('Failed to update order via API:', error);
      
      // API失败时，尝试在本地更新
      try {
        const index = this.orders.findIndex(order => order.id === updatedOrder.id);
        if (index !== -1) {
          this.orders[index] = updatedOrder;
          this.saveToLocalStorage();
          this.notifyListeners();
          return true;
        }
        return false;
      } catch (localError) {
        console.error('Failed to update order locally:', localError);
        throw localError;
      }
    }
  }
}

// 导出单例实例
export default new OrderStore();